package com.pf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pf.commom.enums.UserStatusEnum;
import com.pf.dto.PageBaseResp;
import com.pf.dto.request.UserAddReq;
import com.pf.dto.request.UserListReq;
import com.pf.dto.request.UserUpdReq;
import com.pf.dto.response.UserListResp;
import com.pf.mapper.UserMapper;
import com.pf.mapper.entity.UserEntity;
import com.pf.service.UserService;
import com.pf.utils.DTOUtils;
import com.pf.utils.PageUtils;
import com.pf.utils.StringToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/8/27
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageBaseResp<UserListResp> getUserPageList(UserListReq userReq) {
        Page<UserListReq> page = new Page<>(userReq.getCurrent(), userReq.getSize());
        IPage<UserListResp> userPage = userMapper.getUserPageList(page, userReq);
        return PageUtils.buildPageBaseResp(userPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(UserAddReq user) {
        UserEntity userEntity = DTOUtils.copyToNewObj(user, UserEntity.class);
        userEntity.setUserId(StringToolsUtils.uuid());
        userEntity.setUserStatus(UserStatusEnum.ENABLED.getCode());
        userMapper.insert(userEntity);
    }

    @Override
    public void updateUser(UserUpdReq user) {
        UserEntity userEntity = getUserById(user.getUserId());
        DTOUtils.copyToObj(user, userEntity);
        userMapper.updateById(userEntity);
    }


    private UserEntity getUserById(String userId) {
        return userMapper.selectOne(new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getUserId, userId)
                .eq(UserEntity::getIsDeleted, 0)
        );
    }
}
